package com.example.tiptravel.view.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CircleOptions;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.example.tiptravel.R;
import com.example.tiptravel.commom.base.BaseFragment;
import com.example.tiptravel.commom.utils.ImageLoader;
import com.example.tiptravel.entity.home.Banner;
import com.example.tiptravel.entity.home.Labels;
import com.example.tiptravel.entity.home.NearBy;
import com.example.tiptravel.entity.home.ScenicsBean;
import com.example.tiptravel.presenter.Presenter;
import com.example.tiptravel.presenter.home.BannerPresenter;
import com.example.tiptravel.presenter.home.LabelPresenter;
import com.example.tiptravel.presenter.home.NearByPresenter;
import com.example.tiptravel.view.activity.MapActivity;
import com.example.tiptravel.view.activity.SpotActivity;
import com.example.tiptravel.view.adapter.LabelsAdapter;
import com.example.tiptravel.view.impl.home.BannerView;
import com.example.tiptravel.view.impl.home.LabelView;
import com.example.tiptravel.view.impl.home.NearbyView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment {


    @BindView(R.id.tv_main_location)
    TextView tvMainLocation;
    @BindView(R.id.tv_main_search)
    TextView tvMainSearch;
    @BindView(R.id.cb_main)
    ConvenientBanner cbMain;
    @BindView(R.id.tv_main_title)
    TextView tvMainTitle;
    @BindView(R.id.tv_main_location_definite)
    TextView tvMainLocationDefinite;
    @BindView(R.id.mv_main)
    MapView mvMain;
    @BindView(R.id.vf_main_scenic)
    ViewFlipper vfMainScenic;
    @BindView(R.id.tv_main_share_location)
    TextView tvMainShareLocation;
    @BindView(R.id.tv_main_recom_spot)
    TextView tvMainRecomSpot;
    @BindView(R.id.tv_main_recom_city)
    TextView tvMainRecomCity;
    @BindView(R.id.tv_main_recom_travel)
    TextView tvMainRecomTravel;
    @BindView(R.id.tv_main_recom_user)
    TextView tvMainRecomUser;
    @BindView(R.id.rclv_main_type)
    RecyclerView rclvMainType;

    public static final String KEY = "Location";
    private AMapLocation aMapLocation;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(AMapLocation aMapLocation) {

        Bundle args = new Bundle();
        args.putParcelable(KEY, aMapLocation);
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        this.aMapLocation = getArguments().getParcelable(KEY);
        initbanner();
        initMap(savedInstanceState);
        initLabels();
        initData();
    }

    /**
     * 初始化主题
     */
    private List<Labels.DataBean> dataLabels = new ArrayList<>();
    private LabelsAdapter adapterLabel;

    private void initLabels() {
        rclvMainType.setLayoutManager(new LinearLayoutManager(getContext()));
        adapterLabel = new LabelsAdapter(dataLabels, getContext());
        rclvMainType.setAdapter(adapterLabel);
    }

    /**
     * 初始化地图
     */
    private UiSettings uiSettings;
    private AMap aMap;

    private void initMap(Bundle savedInstanceState) {
        tvMainLocationDefinite.setText(aMapLocation.getAddress());
        initMapPoint();
        mvMain.onCreate(savedInstanceState);
    }

    private void initMapPoint() {
        aMap = mvMain.getMap();
        uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);
        uiSettings.setAllGesturesEnabled(false);
        NearByPresenter presenter = new NearByPresenter(new NearbyView() {
            @Override
            public void onSuccess(NearBy nearBy) {
                if (nearBy != null && nearBy.getStatus().equals("1")) {
                    LatLng latLng01 = new LatLng(Double.valueOf(nearBy.getData().getRegion().getMin().getLat()), Double.valueOf(nearBy.getData().getRegion().getMax().getLng()));
                    LatLng latLng02 = new LatLng(Double.valueOf(nearBy.getData().getRegion().getMax().getLat()), Double.valueOf(nearBy.getData().getRegion().getMin().getLng()));
                    LatLngBounds latbounds = new LatLngBounds(latLng01, latLng02);
                    LatLng latLng03 = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latbounds, 1));

                    MarkerOptions options = new MarkerOptions();
                    options.icon(BitmapDescriptorFactory.fromResource(R.mipmap.amap_my_location));
                    options.position(latLng03);
                    aMap.addMarker(options);

                    MarkerOptions options2 = new MarkerOptions();
                    options2.icon(BitmapDescriptorFactory.fromResource(R.mipmap.amap_my_location_cricle));
                    LatLng latLng04 = new LatLng(aMapLocation.getLatitude() - 0.45, aMapLocation.getLongitude());
                    options2.position(latLng04);
                    aMap.addMarker(options2);

                    //设置景点
                    List<ScenicsBean> list = nearBy.getData().getScenics();
                    for (int i = 0; i < list.size(); i++) {
                        MarkerOptions options3 = new MarkerOptions();
                        options3.icon(BitmapDescriptorFactory.fromResource(R.mipmap.amap_point_default));
                        LatLng latLng05 = new LatLng(Double.valueOf(list.get(i).getGeo().getLat()), Double.valueOf(list.get(i).getGeo().getLng()));
                        options3.position(latLng05);
                        options3.title("123");
                        options3.snippet("123");
                        aMap.addMarker(options3);


                        TextView tv = new TextView(getContext());
                        tv.setText(list.get(i).getScenicName() + "  距你" + list.get(i).getDistance() + "km");
                        tv.setTextSize(12);
                        Drawable left = getResources().getDrawable(R.mipmap.location_type_spot_ico);
                        tv.setCompoundDrawables(left, null, null, null);
                        vfMainScenic.addView(tv);
                    }

                    vfMainScenic.startFlipping();
                    final List<Marker> mapScreenMarkers = aMap.getMapScreenMarkers();

                    new Thread() {
                        @Override
                        public void run() {
                            while (true) {
                                for (int i = 0; i < mapScreenMarkers.size(); i++) {
                                    Message msg = new Message();
                                    msg.obj = mapScreenMarkers.get(i);
                                    handler.sendMessage(msg);
                                    try {
                                        Thread.sleep(5000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }.start();
                }
            }

            @Override
            public void onFailure(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        Map<String, String> map = new HashMap<>();
        map.put("version", "android_3.8.1");
        map.put("lat", String.valueOf(aMapLocation.getLatitude()));
        map.put("lng", String.valueOf(aMapLocation.getLongitude()));
        presenter.getNearByData(map);
    }

    //设置跳转
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Marker marker = (Marker) msg.obj;
            marker.showInfoWindow();

            aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {

                @Override
                public View getInfoWindow(Marker marker) {
                    ImageView iv = new ImageView(getContext());
                    iv.setImageResource(R.mipmap.amap_select_point);
                    iv.setScaleType(ImageView.ScaleType.FIT_XY);
                    iv.setBackgroundColor(Color.alpha(0));
                    return iv;
                }

                @Override
                public View getInfoContents(Marker marker) {

                    return null;
                }
            });

        }
    };

    /**
     * 加载头部数据
     */
    private List<Banner.DataBean> banners = new ArrayList<>();

    private void initbanner() {
        cbMain.setPages(new CBViewHolderCreator<CBHolder>() {

            @Override
            public CBHolder createHolder() {
                return new CBHolder();
            }
        }, banners)
                .setManualPageable(false);
    }

    public class CBHolder implements Holder<Banner.DataBean> {

        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, Banner.DataBean data) {
            ImageLoader.getInstance().displayImage(data.getPic(), context, imageView, R.mipmap.bg_scenic_list_media, R.mipmap.bg_scenic_list_media);
        }
    }
    //------end---------//

    @Override
    protected void initData() {
        BannerPresenter bannerPresenter = new BannerPresenter(new BannerView() {
            @Override
            public void onSuccess(Banner banner) {
                if (banner != null && banner.getStatus().equals("1")) {
                    banners.addAll(banner.getData());
                    cbMain.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        LabelPresenter labelPresenter = new LabelPresenter(new LabelView() {
            @Override
            public void onSuccess(Labels labels) {
                if (labels != null && labels.getStatus().equals("1")) {
                    dataLabels.addAll(labels.getData());
                    adapterLabel.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        Map<String, String> map = new HashMap<>();
        map.put("version", "android_3.8.1");
        map.put("city_id", "");
        bannerPresenter.getBannerData(map);
        labelPresenter.getLabelData(map);
    }


    @OnClick({R.id.tv_main_location, R.id.tv_main_search, R.id.tv_main_location_definite, R.id.tv_main_share_location, R.id.tv_main_recom_spot, R.id.tv_main_recom_city, R.id.tv_main_recom_travel, R.id.tv_main_recom_user, R.id.fl_home})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_main_location:
                break;
            case R.id.tv_main_search:
                break;
            case R.id.tv_main_location_definite:
                break;
            case R.id.tv_main_share_location:
                break;
            case R.id.tv_main_recom_spot:
                Intent intent = new Intent(getContext(), SpotActivity.class);
                getContext().startActivity(intent);
                break;
            case R.id.tv_main_recom_city:
                break;
            case R.id.tv_main_recom_travel:
                break;
            case R.id.tv_main_recom_user:
                break;
            case R.id.fl_home:
                Intent intentmap = new Intent(getContext(), MapActivity.class);
                getContext().startActivity(intentmap);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mvMain.onResume();
        cbMain.startTurning(3000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mvMain.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        cbMain.stopTurning();
        vfMainScenic.stopFlipping();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mvMain.onDestroy();
        cbMain.stopTurning();
        if (handler != null) {
            handler = null;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mvMain.onSaveInstanceState(outState);
    }
}
